import request from '../../utils/request'
import { TicketStatus } from '../../utils/constant'
import Toast from '@vant/weapp/toast/toast'
import { formatNumber } from '../../utils/util'

Page({
  data: {
    show: false,
    actions: [{
      name: '普通缴费',
      subname: '自动选择个人罚单进行缴费'
    }, {
      name: '高级缴费',
      subname: '输入罚单编号进行缴费'
    }],
    visible: {
      ticketFormVisible: false,
      ticketInfoVisible: false,
      paymentButtonVisible: false
    },
    paymentMoney: '',
    ticketId: '',
    ticket: {
      id: '',
      waitFine: '',
      overdueFee: '',
      waitOverdueFee: '',
      ticketStatusName: ''
    }
  },
  onOpen() {
    this.setData({ show: true })
  },
  onClose() {
    this.setData({ show: false })
  },
  onSelect(e) {
    if (e.detail.name === '普通缴费') {
      this.setData({
        visible: {
          ticketFormVisible: false,
          ticketInfoVisible: false,
          paymentButtonVisible: true
        }
      })
    } else if (e.detail.name === '高级缴费') {
      this.setData({
        visible: {
          ticketFormVisible: true,
          ticketInfoVisible: false,
          paymentButtonVisible: false
        }
      })
    }
  },
  async queryTicket() {
    if (!/^\d+$/.test(this.data.ticketId)) {
      Toast.fail('罚单编号只能由数字组成')
      return
    }
    const data = await request.get(`/mvs/ticket/info/payment/${this.data.ticketId}`)
    this.setData({
      ticket: { 
        id: data.ticket.id, 
        waitFine: formatNumber(data.ticket.waitFine) + ' 元',
        overdueFee: formatNumber(data.ticket.overdueFee) + ' 元',
        waitOverdueFee: formatNumber(data.ticket.waitOverdueFee) + ' 元',
        ticketStatusName: TicketStatus[data.ticket.ticketStatus] },
      visible: { ticketFormVisible: true, ticketInfoVisible: true, paymentButtonVisible: true }
    })
  },
  paymentHandle() {
    wx.showModal({
      title: '缴费',
      editable: true,
      placeholderText: '请输入缴费金额(元)',
      success: async (res) => {
        if (res.confirm) {
          if (!/^\d+(\.\d{1,2})?$/.test(res.content)) {
            Toast.fail('缴费金额必须为最多两位小数的正数')
            return
          }
          const money = parseFloat(res.content)
          // 普通缴费
          if (!this.data.visible.ticketInfoVisible) {
            const data = await request.post('/mvs/ticket/payment', { payMoney: money })
            Toast.success(data.msg)
          } else {  // 高级缴费
            if (money > this.data.ticket.waitFine + this.data.ticket.waitOverdueFee) {
              Toast.fail('缴费金额过多')
              return
            }
            const data = await request.post('/mvs/ticket/payment', { payMoney: money, ticketId: this.data.ticketId })
            Toast.success(data.msg)
            await this.queryTicket()
          }
        }
      }
    })
  }
})